package org.example.laboratorymanagement.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.example.laboratorymanagement.pojo.Labor;
import org.example.laboratorymanagement.pojo.PageBean;
import org.example.laboratorymanagement.pojo.Result;
import org.example.laboratorymanagement.service.LaborService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@CrossOrigin
@Slf4j
@RequestMapping("/labors")
@RestController
public class LaborController {

    @Autowired
    private LaborService laborService;

    @GetMapping
    public Result listTeachers(@RequestParam(defaultValue = "1") Integer page,
                               @RequestParam(defaultValue = "10") Integer pageSize,
                               String name, String local, String e) {
        log.info("模糊查询实验室，参数：{},{},{},{},{}",page,pageSize,name,local,e);

        PageBean pageBean = laborService.pagelabors(page, pageSize, name, local,e);

        return Result.success(pageBean);
    }

    @DeleteMapping("/{ids}")
    public Result delete(@PathVariable List<Integer> ids){
        log.info("批量删除实验室ID操作，ids：{}",ids);
        laborService.delete(ids);
        return Result.success();

    }

    @PutMapping
    public Result update(@RequestBody Labor labor){
        log.info("修改实验室：{}",labor);

        laborService.update(labor);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result selectById(@PathVariable Integer id){
        log.info("获取实验室ID：{}", id);
        Labor l = laborService.selectById(id);
        return Result.success(l);
    }

    @PostMapping
    public Result add(@RequestBody Labor labor){
        log.info("新增实验室：{}",labor);
        laborService.add(labor);
        return Result.success();
    }

    @GetMapping("/selectAll")
    public Result selectAll(){
        log.info("查询全部数据：");
        List<Labor> list = laborService.selectAll();
        return Result.success(list);

    }

    @PostMapping("/insertBatch")
    public Result insertBatch(MultipartFile file) throws IOException {
        ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
        List<Labor> labors = reader.readAll(Labor.class);
        log.info("批量添加实验室：{}",labors);
        try {
            laborService.insertBatch(labors);
        } catch (Exception e) {
            return Result.error("数据库批量导入出错！");
        }

        return Result.success();
    }

}
